package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;
import service.SetmealService;

import java.util.HashMap;
import java.util.List;

@Transactional
@Service(interfaceClass = SetmealService.class )
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public void add(Setmeal setmeal, int[] checkgroupIds) {

        //1.新增套餐的数据
        setmealDao.addSetmeal(setmeal);
        //图片名称存放到redis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());

        if(checkgroupIds!=null&&checkgroupIds.length>0){

            Integer mealId = setmeal.getId();
//            //2.重新建立检查组和套餐关系  绑定套餐和检查组的多对多关系
            set_t_setmeal_checkgroup(mealId,checkgroupIds);
        }

    }

    /**
     * 分页
     * @param
     * @param
     * @param
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean, QueryPageBean queryPageBean1) {
        //设置分页数据
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page=setmealDao.findPage(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 查询所有的套餐
     * @return
     */
    @Override
    public List<Setmeal> findAll() {

        return setmealDao.findAll();
    }

//  在根据id查询套餐时，同时将此套餐包含的检查组都查询出来，并且将检查组包含的检查项都查询出来
    @Override
    public Setmeal findById(int id) {


        return setmealDao.findById(id);
    }

    //3.重新建立检查组和套餐关系  绑定套餐和检查组的多对多关系
    public void set_t_setmeal_checkgroup(Integer mealId,int[] checkgroupIds){
        HashMap<String,Integer> hm = new HashMap();

        for (int checkitemId : checkgroupIds) {
            hm.put("mealid", mealId);
            hm.put("checkgroupIds", checkitemId);
            setmealDao.setSetmealAndCheckGroup(hm);

        }


    }

}


